package xin.marcher.module.seller.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xin.marcher.module.common.core.PageResult;
import xin.marcher.module.common.exception.BaseBizException;
import xin.marcher.module.common.exception.ProductErrorCodeEnum;
import xin.marcher.module.seller.domain.dto.SellerGroupRelationDTO;
import xin.marcher.module.seller.domain.dto.SellerGroupRelationResultDTO;
import xin.marcher.module.seller.domain.request.SellerGroupRelationRequest;
import xin.marcher.module.seller.domain.request.SellerGroupRequest;
import xin.marcher.module.seller.domain.request.SellerInfoRequest;
import xin.marcher.module.seller.domain.response.SellerGroupResponse;
import xin.marcher.module.seller.domain.response.SellerInfoResponse;
import xin.marcher.module.seller.repository.SellerRepository;
import xin.marcher.module.seller.service.SellerGroupRelationService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 *
 */
@Service
@Slf4j
public class SellerGroupRelationServiceImpl implements SellerGroupRelationService {

    @Resource
    private SellerRepository sellerRepository;

    /**
     * 新增卖家组与卖家关系
     *
     * @param request
     * @return
     */
    @Override
    public SellerGroupRelationResultDTO saveSellerGroupRelationInfo(SellerGroupRelationRequest request) {
        // 参数检查
        checkSaveSellerGroupRelationRequest(request);
        // 卖家ID类型是否有和卖家组的类型不一致的
        checkAndGetSellerTypeConsistency(request);
        // 过滤掉已经添加过相同关系的卖家与卖家组关系
        request = filterIfExist(request);
        // 批量插入
        log.info("request:{}", JSON.toJSONString(request));
        sellerRepository.saveSellerGroupRelationInfo(request);
        SellerGroupRelationResultDTO result = new SellerGroupRelationResultDTO(request.getSellerGroupId(),
                request.getSellerIdList(), Boolean.TRUE);
        return result;
    }

    private SellerGroupRelationRequest filterIfExist(SellerGroupRelationRequest request) {
        SellerGroupRelationRequest relationRequest = SellerGroupRelationRequest.builder()
                .sellerIdList(request.getSellerIdList())
                .sellerGroupId(request.getSellerGroupId())
                .build();

        List<SellerGroupRelationDTO> sellerGroupRelationDTOS = sellerRepository
                .querySellerGroupRelationInfo(relationRequest);
        List<Long> existSellerIds = sellerGroupRelationDTOS.stream().map(relation -> relation.getSellerId())
                .collect(Collectors.toList());
        List<Long> filteredSellerIds = request.getSellerIdList().stream()
                .filter(sellerId -> !existSellerIds.contains(sellerId))
                .collect(Collectors.toList());
        log.info("filteredSellerIds:{}", JSON.toJSONString(filteredSellerIds));
        return SellerGroupRelationRequest.builder()
                .sellerGroupId(request.getSellerGroupId())
                .sellerIdList(filteredSellerIds)
                .build();
    }

    /**
     * 检查卖家ID集合中是否存在和卖家组类型不一致的卖家
     *
     * @param request
     */
    private void checkAndGetSellerTypeConsistency(SellerGroupRelationRequest request) {
        // 查询卖家组信息
        SellerGroupRequest groupRequest = new SellerGroupRequest();
        groupRequest.setSellerGroupId(request.getSellerGroupId());
        PageResult<SellerGroupResponse> pageResult = sellerRepository.querySellerGroup(groupRequest);

        List<SellerGroupResponse> groupList = pageResult.getContent();
        // 卖家组不存在
        if (CollectionUtils.size(groupList) <= 0) {
            throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
        }

        // 查询卖家信息
        SellerInfoRequest sellerRequest = new SellerInfoRequest();
        sellerRequest.setSellerIdList(request.getSellerIdList());
        Optional<List<SellerInfoResponse>> sellerInfoListOps = sellerRepository.querySellerInfo(sellerRequest);
        // 卖家不存在
        if (!sellerInfoListOps.isPresent()) {
            throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
        }

        List<SellerInfoResponse> sellerInfoList = sellerInfoListOps.get();
        // 卖家组类型
        Integer sellerGroupType = groupList.get(0).getSellerGroupType();
        long count = sellerInfoList.stream().filter(sellerInfoResponse -> {
            if (!sellerInfoResponse.getSellerType().equals(sellerGroupType)) {
                return true;
            }
            return false;
        }).count();
        // 卖家ID中存在类型与卖家组中的不一致
        if (count > 0) {
            throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
        }
    }

    /**
     * 查询卖家参数校验
     *
     * @param request
     */
    private void checkSaveSellerGroupRelationRequest(SellerGroupRelationRequest request) {
        if (Objects.isNull(request)) {
            throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
        }

        if (Objects.isNull(request.getSellerGroupId())) {
            throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
        }

        if (CollectionUtils.isEmpty(request.getSellerIdList())) {
            throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
        }
    }

    /**
     * 查询卖家组与卖家关系信息
     *
     * @param request
     * @return
     */
    @Override
    public List<SellerGroupRelationDTO> querySellerGroupRelationInfo(SellerGroupRelationRequest request) {
        return sellerRepository.querySellerGroupRelationInfo(request);
    }

    /**
     * 根据卖家id和卖家组id删除卖家与卖家组关系
     *
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteBySellerId(SellerGroupRelationRequest request) {
        // 校验参数
        checkSaveSellerGroupRelationRequest(request);
        return sellerRepository.deleteRelationBySellerId(request.getSellerIdList(), request.getSellerGroupId());
    }
}